package com.jxlst.channel.pro.util;


import com.jxlst.channel.pro.constant.ConfigDict;
import com.jxlst.channel.pro.constant.DateFormatDict;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 请求渠道工具类
 * <p>
 * 1.
 * </p>
 *
 * @author : wukong
 * @version : 1.0.0
 * @date : 2018/7/18
 */
@Slf4j
@NoArgsConstructor
public final class RequestUtil {

    public static String sign(SortedMap<String, String> parameters, String key) {
        StringBuffer sourceStr = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)) {
                sourceStr.append(k + "=" + v + "&");
            }
        }
        sourceStr = sourceStr.append("key=" + key);
        log.info("签名原串:{}", sourceStr);
        return SecurityUtil.md5DesEncrypt(sourceStr.toString());
    }

    private static SortedMap<String, String> packageBaseParams() {
        SortedMap<String, String> params = new TreeMap<>();
        params.put("merchantId", ConfigDict.MERCHANT_ID);
        params.put("agencyType", "hljcd");
        params.put("transTime", DateTime.now().toString(DateFormatDict.YYYYMMDDHHMMSS));
        return params;
    }

    public static SortedMap<String, String> packageReq(SortedMap<String, String> params) {
        String sign = RequestUtil.sign(params, ConfigDict.KEY);
        log.info("sign:{}", sign);
        params.put("sign", sign);
        return params;
    }

    public static SortedMap<String, String> packageParams(Object obj) throws IllegalAccessException {
        SortedMap<String, String> parameters = RequestUtil.packageBaseParams();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field item : fields) {
            item.setAccessible(true);
            parameters.put(item.getName(), String.valueOf(item.get(obj)));
        }
        return parameters;
    }
}
